package com.jshan.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jshan.base.dto.TableCreateRequest;
import com.jshan.base.entity.TableInfo;
import com.jshan.base.vo.Result;
import com.jshan.common.annotation.OperationLog;
import com.jshan.service.TableInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

@Tag(name = "数据库表管理")
@RestController
@RequestMapping("/table")
public class TableInfoController {

    @Resource
    private TableInfoService tableInfoService;

    @Operation(summary = "获取数据库表列表")
    @Parameter(name = "page", description = "页码", required = true)
    @Parameter(name = "pageSize", description = "每页大小", required = true)
    @Parameter(name = "tableName", description = "表名（可选，模糊查询）")
    @GetMapping("/list")
    @OperationLog("查询数据库表列表")
    @SaCheckPermission("tools:list")
    public Result getTableList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String tableName) {

        return Result.ok(tableInfoService.getTableList(page, pageSize, tableName));
    }

    @Operation(summary = "创建数据表")
    @PostMapping("/create")
    @OperationLog("创建数据表")
    @SaCheckPermission("tools:list:add")
    public Result createTable(@RequestBody TableCreateRequest request) {
        try {
            tableInfoService.createTable(request);
            return Result.ok();
        } catch (RuntimeException e) {
            if (e.getMessage() != null && e.getMessage().contains("表已存在")) {
                return Result.fail(500, "表已存在");
            }
            throw e;
        }
    }
}
